package mutil

import (
	"bytes"
	"gitee.com/dennis-mxx/mxx-core/mlogger"
	"io"
	"net/http"
	"strings"
)

const JsonHeader = "application/json;charset=utf-8"
const FormHeader = "application/x-www-form-urlencoded;charset=utf-8"
const Get = "GET"
const Post = "POST"
const EmptyJson = "{}"

type HttpRequest struct {
	Url     string
	Data    map[string]interface{}
	Body    string
	UrlData map[string]string
	Method  string
	Header  map[string]string
}

type Response struct {
}

func (domain *HttpRequest) PostForm() (*http.Response, error) {
	domain.setHeader(HeaderNames.ContentType, FormHeader)
	if domain.Data != nil && domain.Body == "" {
		domain.Body = Strings.EncodeForm(domain.Data)
	}
	return domain.doPost()
}
func (domain *HttpRequest) PostJson() (*http.Response, error) {
	domain.setHeader(HeaderNames.ContentType, JsonHeader)
	if domain.Data != nil && domain.Body == "" {
		if str, err := Json.ToJSONString(domain.Data); err != nil {
			return nil, err
		} else {
			domain.Body = str
		}
	} else {
		domain.Body = EmptyJson
	}
	return domain.doPost()
}
func (domain *HttpRequest) GetUrl() (*http.Response, error) {
	domain.setHeader(HeaderNames.ContentType, FormHeader)
	return domain.doPost()
}

func (domain *HttpRequest) doPost() (*http.Response, error) {
	defer mlogger.FormatException()
	var reader io.Reader

	if strings.EqualFold(Post, domain.Method) {
		reader = strings.NewReader(domain.Body)
	}

	if domain.UrlData != nil {
		domain.Url = Strings.spliceUrl(domain.Url, domain.UrlData)
	}
	request, error := http.NewRequest(domain.Method, domain.Url, reader)
	if error != nil {
		return nil, error
	}
	for key, value := range domain.Header {
		request.Header.Add(key, value)
	}

	response, error := http.DefaultClient.Do(request)
	return response, error
}
func (domain *HttpRequest) ReadResponse(response *http.Response) string {
	buffer := bytes.Buffer{}
	for b := make([]byte, 1024); ; {
		length, _ := response.Body.Read(b)
		if length == 0 {
			break
		}
		buffer.Write(b[:length])
	}
	return buffer.String()
}
func (domain *HttpRequest) setHeader(headerName string, headerValue string) {
	if domain.Header == nil {
		domain.Header = map[string]string{}
	}
	domain.Header[headerName] = headerValue
}
